package com.gzkemays.music.expcetion;

import com.gzkemays.common.GResult;
import com.gzkemays.enums.GCommonEnums;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLSyntaxErrorException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestControllerAdvice
@Slf4j
public class ExceptionHandler {
  private static Map<Class<? extends Throwable>, GCommonEnums> EXCEPTIONS = new HashMap<>();;

  static {
    EXCEPTIONS.put(HttpMessageNotReadableException.class, GCommonEnums.DATA_ERROR);
    EXCEPTIONS.put(HttpMediaTypeNotSupportedException.class, GCommonEnums.REQ_ERROR_SUPPORT);
    EXCEPTIONS.put(SQLSyntaxErrorException.class, GCommonEnums.SQL_OPERA_ERROR);
    EXCEPTIONS.put(SQLException.class, GCommonEnums.SQL_ERROR);
  }

  @org.springframework.web.bind.annotation.ExceptionHandler(value = MusicException.class)
  public GResult MusicException(MusicException exception) {
    log.error("消息异常: {}", exception.getMsg());
    return GResult.init().code(exception.getCode()).msg(exception.getMsg()).build();
  }

  @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class)
  public GResult Exception(Exception e) {
    log.error("Exception 异常信息: {}", e.getMessage());
    log.error("异常类: {}", e.getClass());
    log.error("异常原因: {}", e.getCause());
    if (Objects.nonNull(EXCEPTIONS.get(e.getClass()))) {
      return GResult.init().create(EXCEPTIONS.get(e.getClass()), null);
    }
    return GResult.init().code(9999).msg("未知异常").build();
  }
}
